package cn.safekeeper.plugin.console;
import org.apache.logging.log4j.core.util.StringBuilderWriter;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * banner打印
 * @author skylark
 */
public class ConsoleApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        if (!(applicationContext instanceof AnnotationConfigApplicationContext)) {
            initialize("/logo.txt");
        }
    }
    protected void initialize(String resourceLocation) {
        InputStream inputStream = null;
        String bannerText = null;

        try {
            if (resourceLocation != null) {
                inputStream = ConsoleApplicationContextInitializer.class.getResourceAsStream(resourceLocation);
                bannerText = toString(inputStream, "UTF-8");
            }
        } catch (Exception ignored) {
        } finally {
            System.out.println(bannerText);
        }
    }

    public static String toString(InputStream input, String encoding) throws IOException {
        return toString(input, StandardCharsets.UTF_8);
    }

    public static String toString(InputStream input, Charset encoding) throws IOException {
        StringWriter sw = new StringWriter();
        copy((InputStream)input, (Writer)sw, (Charset)encoding);
        return sw.toString();
    }

    public static void copy(InputStream input, Writer output, Charset inputEncoding) throws IOException {
        InputStreamReader in = new InputStreamReader(input, inputEncoding);
        copy((Reader)in, (Writer)output);
    }

    public static int copy(Reader input, Writer output) throws IOException {
        long count = copyLarge(input, output);
        return count > 2147483647L ? -1 : (int)count;
    }
    public static long copyLarge(Reader input, Writer output) throws IOException {
        return copyLarge(input, output, new char[4096]);
    }

    public static long copyLarge(Reader input, Writer output, char[] buffer) throws IOException {
        long count;
        int n;
        for(count = 0L; -1 != (n = input.read(buffer)); count += (long)n) {
            output.write(buffer, 0, n);
        }
        return count;
    }



}
